package com.tensquare.friend.controller;

import com.netflix.discovery.converters.Auto;
import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.pojo.NoFriend;
import com.tensquare.friend.service.FriendService;
import com.tensquare.friend.service.NoFriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/7/29 15:22
 */
@RestController
@RequestMapping("friend")
public class FriendController {
    @Autowired
    private FriendService friendService;
    @Autowired
    private NoFriendService noFriendService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserClient userClient;
    //1.添加好友
    @PutMapping("like/{friendid}/{type}")
    public Result addFriend(@PathVariable String friendid, @PathVariable String type){
        //1.1)得到请求作用域中的claims这个对象，看是否有权限
        Claims claims = (Claims) request.getAttribute("claims");
        //1.2)如果对象存在
        if(claims != null){
            //1.2.1)添加好友
            if(type.equals("1")){       //代表喜欢
                //① 添加好友
                int count = friendService.addFriend(claims.getId(),friendid);
                //② 更新关注数与粉丝数
                userClient.incfollow(claims.getId(),1);
                userClient.incfans(friendid,1);
                //③ 如果count=0，代表重复添加
                if(count == 0){
                    return new Result(false,StatusCode.REPERROR,"重复添加好友！");
                }
            }else{                  //添加非好友
                noFriendService.add(claims.getId(),friendid);
            }
            return new Result(true,StatusCode.OK,"添加好友成功！");
        }else{
            return new Result(false, StatusCode.ACCESSERROR,"无权访问！");
        }
    }
    //2.删除好友
    @DeleteMapping("{friendid}")
    public Result deleteFriend(@PathVariable String friendid){
        //1.1)得到请求作用域中的claims这个对象，看是否有权限
        Claims claims = (Claims) request.getAttribute("claims");
        //1.2)判断是否存在claims
        if(claims != null){
            //1.2.1)从好友表删除记录，修改对方的islike为0，向非好友表添加一条记录
            friendService.deleteFriend(claims.getId(),friendid);
            //1.2.2)修改粉丝数与关注数
            userClient.incfollow(claims.getId(),-1);
            userClient.incfans(friendid,-1);
            return new Result(true,StatusCode.OK,"删除好友成功！");
        }else{
            return new Result(false, StatusCode.ACCESSERROR,"无权访问！");
        }
    }
}
